﻿#include "devicecamera.h"
#include "common.h"

DeviceCamera::DeviceCamera(QLabel *camera_show) {
    initCamera(camera_show);
}

DeviceCamera::~DeviceCamera() {
    if(camera != NULL) {
        delete camera;
        camera = NULL;
    }
    if(imageCapture != NULL) {
        delete imageCapture;
        imageCapture = NULL;
    }
    if(imageCapture != NULL) {
        delete imageCapture;
        imageCapture = NULL;
    }
}

int DeviceCamera::initCamera(QLabel *cameraLabel) {
    //1、创建摄像头对象
    camera = new QCamera(QCameraInfo::defaultCamera());

    //2、创建取景器对象，也就是用于显示摄像头画面的控件，并且给该对象设置一个父控件
    viewfinder = new QCameraViewfinder(cameraLabel);
    viewfinder->resize(cameraLabel->size());
    viewfinder->show();

    //3、绑定摄像头 和摄像头画面控件
    camera->setViewfinder(viewfinder);

    //4、打开摄像头
    camera->start(); // to start the viewfinder
    //5、捕获图像，我们需要初始化一个新的QCameraImageCapture对象
    imageCapture = new QCameraImageCapture(camera);
    //imageCapture 该对象就会自动去捕捉摄像头的数据，当捕获时，那么它就会发送一个信号
    camera->setCaptureMode(QCamera::CaptureStillImage);

    //void imageCaptured(int id, const QImage &preview) preview为图像数据
    connect(imageCapture, &QCameraImageCapture::imageCaptured, this, &DeviceCamera::captureCameraToSave);
    return 0;
}

void DeviceCamera::captureCameraToSave(int id, const QImage &preview) {
    preview.save(*currentPicPath, "BMP");
}

void DeviceCamera::capturePic(QString picPath) {
    currentPicPath = &picPath;
    //拍照
    imageCapture->capture();
    Common::sleep(100);  // 等待图片保存
    currentPicPath = NULL;
}

